package com.smart.service;

import com.smart.dao.LoginLogDao;
import com.smart.dao.UserDao;
import com.smart.domain.LoginLog;
import com.smart.domain.User;
import com.smart.exception.UserExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//用户管理服务器，负责执行查询用户，注册用户、锁定用户等操作
@Service
public class UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private LoginLogDao loginLogDao;

    //注册一个新用户，如果用户名已经存在，则抛出UserExistException异常
    public void register(User user) throws UserExistException {
        User u = this.getUserByUserName(user.getUserName());
        if (null != u) {
            throw new UserExistException("用户名已经存在");
        } else {
            user.setCredit(100);
            user.setUserType(1);
            userDao.save(user);
        }
    }

    //根据用户名查找用户
    public User getUserByUserName(String userName) {
        return userDao.getUserByUserName(userName);
    }

    //根据userId加载User
    public User getUserById(Long userId) {
        return userDao.get(userId);
    }

    //将用户锁定
    public void lockUser(String userName) {
        User user = userDao.getUserByUserName(userName);
        user.setLocked(User.USER_LOCK);
        userDao.update(user);
    }

    //解除用户锁定
    public void unlockUser(String userName) {
        User user = userDao.getUserByUserName(userName);
        user.setLocked(User.USER_UNLOCK);
        userDao.update(user);
    }

    //根据用户名为条件，执行模糊查询操作
    public List<User> queryUserByUserName(String userName) {
        return userDao.queryUserByUserName(userName);
    }

    //获取所有用户
    public List<User> getAllUsers() {
        return userDao.loadAll();
    }

    //登录成功
    public void loginSuccess(User user) {
        user.setCredit(user.getCredit() + 5);
        LoginLog loginLog = new LoginLog();
        loginLog.setUser(user);
        loginLog.setLoginDatetime(new Date());
        loginLog.setIp(user.getLastIp());
        userDao.update(user);
        loginLogDao.update(loginLog);
    }
}
